package com.jianyun.jyzs.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import com.facebook.imageutils.BitmapUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;




/**
 * [从本地选择图片以及拍照工具类，完美适配2.0-5.0版本]
 *
 * @author huxinwu
 * @version 1.0
 * @date 2015-1-7
 **/
public class PhotoUtils {

    private final String tag = PhotoUtils.class.getSimpleName();

    private final int LARGE_PORTRAIT_SIZE = 600;
    private final int SMALL_PORTRAIT_SIZE = 150;
    private static int SMALL_PORTRATT_MIN_SIZE = 60;
    private static int COMPRESSED_QUALITY = 50;
    /**
     * 裁剪图片成功后返回
     **/
    public static final int INTENT_CROP = 2;
    /**
     * 拍照成功后返回
     **/
    public static final int INTENT_TAKE = 3;
    /**
     * 拍照成功后返回
     **/
    public static final int INTENT_SELECT = 4;

    private Uri uploadFileUri;

    private Uri thumbUri;

    private String targetId;

    private String uploadName;
    private boolean isPinSelect = false;

    /**
     * PhotoUtils对象
     **/
    private OnPhotoResultListener onPhotoResultListener;

    public PhotoUtils(OnPhotoResultListener onPhotoResultListener) {
        this.onPhotoResultListener = onPhotoResultListener;
    }
    public PhotoUtils() {

    }
    public void setTargetId(String targetId) {
        this.targetId = targetId;
    }

    public void setName(String name) {
        uploadName = name;
    }

    public Uri getUploadFileUri() {
        return uploadFileUri;
    }

    public void setUploadFileUri(Uri uri) {
        uploadFileUri = uri;
    }

    /**
     * 拍照
     *
     * @param
     * @return
     */
    public void takePicture(Activity activity) {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, buildUri(activity));
            if (!isIntentAvailable(activity, intent)) {
                return;
            }
            activity.startActivityForResult(intent, INTENT_TAKE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 选择一张图片
     * 图片类型，这里是image/*，当然也可以设置限制
     * 如：image/jpeg等
     *
     * @param activity Activity
     */
    @SuppressLint("InlinedApi")
    public void selectPicture(Activity activity) {
        try {
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

            if (!isIntentAvailable(activity, intent)) {
                return;
            }
            activity.startActivityForResult(intent, INTENT_SELECT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 选择一张图片
     * 图片类型，这里是image/*，当然也可以设置限制
     * 如：image/jpeg等
     *
     * @param activity Activity
     */
    @SuppressLint("InlinedApi")
    public void selectPicture2(Activity activity) {

        Intent intent = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        activity.startActivityForResult(intent, 90);
//        try {
//            Intent intent = new Intent(Intent.ACTION_PICK, null);
//            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//
//            if (!isIntentAvailable(activity, intent)) {
//                return;
//            }
//            activity.startActivityForResult(intent, 90);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 构建uri
     *
     * @param activity
     * @return
     */
    private Uri buildUri(Activity activity) {
        if (uploadFileUri != null) {
            return uploadFileUri;
        }
        String uploadFileName;
        if (TextUtils.isEmpty(uploadName)) {
            uploadFileName = String.valueOf(System.currentTimeMillis()) + targetId;
            uploadFileName = RongUtils.md5(uploadFileName);
        } else {
            uploadFileName = uploadName;
        }

        uploadFileName = uploadFileName + LARGE_PORTRAIT_SIZE + "X" + LARGE_PORTRAIT_SIZE + ".jpg";
        if (checkSDCard()) {
            uploadFileUri = Uri.fromFile(Environment.getExternalStorageDirectory()).buildUpon().appendPath(uploadFileName).build();
        } else {
            uploadFileUri = Uri.fromFile(activity.getCacheDir()).buildUpon().appendPath(uploadFileName).build();
        }
        //Log.i("test", "拍照图片：" + uploadFileUri + "\n" + Environment.getExternalStorageDirectory() + "\n" + uploadFileName);
        return uploadFileUri;
    }

    private String buildThumbName(Activity activity) {
        String thumbName;
        if (TextUtils.isEmpty(uploadName)) {
            thumbName = String.valueOf(System.currentTimeMillis()) + targetId;
            thumbName = RongUtils.md5(thumbName);
        } else {
            thumbName = uploadName;
        }
        thumbName = thumbName + SMALL_PORTRAIT_SIZE + "X" + SMALL_PORTRAIT_SIZE + ".jpg";
        return thumbName;
    }

    /**
     * 判断SDCard是否存在,并可写
     *
     * @return
     */
    public static boolean checkSDCard() {
        String flag = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(flag);
    }

    /**
     * @param intent
     * @return
     */
    protected boolean isIntentAvailable(Activity activity, Intent intent) {
        PackageManager packageManager = activity.getPackageManager();
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    private boolean corp(Activity activity, Uri uri) {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        cropIntent.setDataAndType(uri, "image/*");
        cropIntent.putExtra("crop", "true");
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        cropIntent.putExtra("outputX", LARGE_PORTRAIT_SIZE);
        cropIntent.putExtra("outputY", LARGE_PORTRAIT_SIZE);
        cropIntent.putExtra("return-data", false);
        cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        Uri cropUri = buildUri(activity);
        cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
        if (!isIntentAvailable(activity, cropIntent)) {
            return false;
        } else {
            try {
                activity.startActivityForResult(cropIntent, INTENT_CROP);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    /**
     * 返回结果处理
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        if (onPhotoResultListener == null) {
            Log.e(tag, "onPhotoResultListener is not null");
            return;
        }

        switch (requestCode) {
            //拍照
            case INTENT_TAKE:
                if (new File(buildUri(activity).getPath()).exists()) {
                    if (corp(activity, buildUri(activity))) {
                        return;
                    }
                    onPhotoResultListener.onPhotoCancel();
                }
                break;

            //选择图片
            case INTENT_SELECT:
                if (isPinSelect()) {
                    if (data != null && data.getData() != null) {
                        onPhotoResultListener.onPhotoResult(data.getData(), null);
                    }
                } else {
                    if (data != null && data.getData() != null) {
                        Uri imageUri = data.getData();
                        if (corp(activity, imageUri)) {
                            return;
                        }
                    }
                    onPhotoResultListener.onPhotoCancel();
                }
                break;

            //截图
            case INTENT_CROP:
                if (resultCode == Activity.RESULT_OK) {
                    Uri largeUrl = uploadFileUri;
                    if (largeUrl != null && new File(largeUrl.getPath()).exists()) {
                        Uri thumbUrl = compressThumbUri(activity, largeUrl);
                        onPhotoResultListener.onPhotoResult(thumbUrl, largeUrl);
                        Log.i("test", "thumbUrl=截图" + thumbUrl.toString());
                    }
                }
                break;
        }
    }

    private Uri compressThumbUri(Activity activity, Uri largeUri) {
        try {
            Bitmap bitmap = BitmapUtilAS.getThumbBitmap(activity, largeUri,
                    SMALL_PORTRAIT_SIZE, SMALL_PORTRATT_MIN_SIZE);
            if (bitmap != null) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSED_QUALITY, outputStream);
                byte[] data = outputStream.toByteArray();
                outputStream.close();

                Uri thumbPath;
                if (checkSDCard()) {
                    thumbPath = Uri.parse(Environment.getExternalStorageDirectory().getPath());
                } else {
                    thumbPath = Uri.parse(activity.getCacheDir().getPath());
                }
                String name = buildThumbName(activity);
                File thumbImage = FileUtils.byte2File(data, thumbPath.toString(), name);

                thumbUri = Uri.parse(thumbImage.getPath());
                if (!bitmap.isRecycled())
                    bitmap.recycle();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return thumbUri;
    }

    /**
     * 删除文件
     *
     * @param uri
     * @return
     */
    public boolean clearCropFile(Uri uri) {
        if (uri == null) {
            return false;
        }

        File file = new File(uri.getPath());
        if (file.exists()) {
            boolean result = file.delete();
            if (result) {
                Log.i(tag, "Cached crop file cleared.");
            } else {
                Log.e(tag, "Failed to clear cached crop file.");
            }
            if (uri == uploadFileUri) {
                uploadFileUri = null;
            } else if (uri == thumbUri) {
                thumbUri = null;
            }
            return result;
        } else {
            Log.w(tag, "Trying to clear cached crop file but it does not exist.");
        }
        if (uri == uploadFileUri) {
            uploadFileUri = null;
        } else if (uri == thumbUri) {
            thumbUri = null;
        }
        return false;
    }

    /**
     * [回调监听类]
     *
     * @author huxinwu
     * @version 1.0
     * @date 2015-1-7
     **/
    public interface OnPhotoResultListener {
        void onPhotoResult(Uri thumbUrl, Uri largeUrl);

        void onPhotoCancel();
    }

    public OnPhotoResultListener getOnPhotoResultListener() {
        return onPhotoResultListener;
    }

    public void setOnPhotoResultListener(OnPhotoResultListener onPhotoResultListener) {
        this.onPhotoResultListener = onPhotoResultListener;
    }


    public boolean isPinSelect() {
        return isPinSelect;
    }

    public void setPinSelect(boolean pinSelect) {
        isPinSelect = pinSelect;
    }
}
